<template>
    <el-dialog v-model="visible" :title="dialogTitle" width="769px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :size="formSize" label-width="90px">
            <el-form-item label="账户名称" prop="username">
                <el-input v-model="ruleForm.username" clearable placeholder="请输入账户名称" />
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickname">
                <el-input v-model="ruleForm.nickname" placeholder="请输入用户昵称" clearable />
            </el-form-item>
            <el-form-item label="关联角色" prop="roleIds">
                <el-select v-model="ruleForm.roleIds" placeholder="请选择关联角色" clearable>
                    <el-option label="超级管理员" value="admin" />
                    <el-option label="普通用户" value="common" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptId">
                <el-cascader
                    v-model="ruleForm.deptId"
                    :options="deptOptions"
                    :props="{ checkStrictly: true, value: 'deptName', label: 'deptName' }"
                    placeholder="请选择部门"
                    clearable
                    class="w100"
                >
                    <template #default="{ node, data }">
                        <span>{{ data.deptName }}</span>
                        <span v-if="!node.isLeaf">({{ data.children.length }})</span>
                    </template>
                </el-cascader>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input v-model="ruleForm.mobile" placeholder="请输入手机号" clearable />
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input v-model="ruleForm.email" placeholder="请输入邮箱" clearable />
            </el-form-item>
            <el-form-item label="性别">
                <el-select v-model="ruleForm.gender" placeholder="请选择性别" clearable>
                    <el-option label="男" :value="1" />
                    <el-option label="女" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户状态">
                <el-switch v-model="ruleForm.status" inline-prompt active-text="正常" inactive-text="禁用" :active-value="1" :inactive-value="0" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button size="default" @click="onCancel">取 消</el-button>
                <el-button type="primary" size="default" @click="onSubmit(ruleFormRef)">保 存</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@/api/system/user/types.ts'
import { Option } from '@/api/types.ts'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { saveUser, updateUser } from '@/api/system/user/index.ts'
import { getRoleOptions } from '@/api/system/role/index.ts'
import { resetForm } from '@/utils/index.ts'

const visible = ref(false)
const dialogTitle = ref('新增用户')

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
/** 表单数据 */
const defaultRuleForm: User.Form = {
    username: '',
    nickname: '',
    roleIds: [],
    status: 1,
}
const ruleForm = reactive<User.Form>({
    username: '',
    nickname: '',
    roleIds: [],
    status: 1,
})
/** 定义校验规则 */
const rules = reactive<FormRules<User.Form>>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
    roleIds: [{ required: true, message: '请选择关联角色', trigger: 'change' }],
    deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
    email: [
        {
            pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
            message: '请输入正确的邮箱地址',
            trigger: 'blur',
        },
    ],
    mobile: [
        {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
        },
    ],
})
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh'])
/** 打开弹窗 */
const openDialog = (item: User.Form | undefined) => {
    ruleFormRef.value?.clearValidate()
    if (item) {
        dialogTitle.value = '编辑用户'
        Object.assign(ruleForm, item)
    } else {
        dialogTitle.value = '新增用户'
        // 使用深拷贝清空表单数据
        resetForm(ruleForm, defaultRuleForm)
    }
    loadRoleOptions()
    loadDeptOptions()
    visible.value = true
}
/** 关闭弹窗 */
const onCancel = () => {
    visible.value = false
}
/** 提交 */
const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (ruleForm.id) {
                updateUser(ruleForm).then(() => {
                    ElMessage.success('保存成功')
                    visible.value = false
                    emit('refresh')
                })
            } else {
                saveUser(ruleForm).then(() => {
                    ElMessage.success('保存成功')
                    visible.value = false
                    emit('refresh')
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

//角色下拉数据
const roleOptions = ref<Option[]>()
const loadRoleOptions = async () => {
    roleOptions.value = await getRoleOptions()
}

//部门下拉数据
const deptOptions = ref<Option[]>([])
const loadDeptOptions = async () => {}

defineExpose({
    openDialog,
})
</script>
